//获取猫咪信息
function getCat(id) {
    const __errorHandle = (obj, err, msg) => {
        $("#name").text("出现错误");
        $("#sub_cat_info").append(`<span class="module"><div>${err}</div>${msg}</span>`);
    };
    $.ajax({
        url: `/cats/get/id/${id}`,
        error: __errorHandle,
        success: (responseJSON) => {
            if (!responseJSON.success) return errorHandle('idCatResultError', responseJSON.error);
            let r = responseJSON.result;
            if (!r) return __errorHandle('', '不存在', `找不到ID为<span style="color:orange;">${id}</span>的猫咪`);
            let target = $("#sub_cat_info");
            let hides = new Set('a aa e'.split(' ')); //ID img color
            for (let rawKey in r) {
                let hide = hides.has(rawKey) ? false : ' ';
                let data = getRealData(rawKey, r[rawKey]);
                if (data.data && getTableKeyClass(rawKey, 'date', 'age')) data.data = parseDate(data.data);
                target.append(`<span data-key="${rawKey}" class="module${hide||' hide_module'}${!hide||data.data?' ':' none_data'}" id="sub_${data.nameValue}"><div>${data.name}</div>${data.data||"暂缺"}</span>`);
            }
            $("#name").text(r.b);
        }
    });
}


//获取猫咪关系网
function getRelation(id) {
    const __errorHandle = (obj, err, msg) => {
        $("#cat_relation").html(`<span><div>${err}</div>${msg}</span>`);
    };
    $.ajax({
        url: `/cats/relation/${id}`,
        error: __errorHandle,
        success: (responseJSON) => {
            if (!responseJSON.success) return errorHandle('idCatRelationError', responseJSON.error);
            let r = responseJSON.result;
            if (!r) return __errorHandle('', '不存在', `找不到ID为<span style="color:orange;">${id}</span>的猫咪`);
            let target = $("#cat_relation canvas");
            let canvas = target[0];
            stage = new JTopo.Stage(canvas);
            // showJTopoToobar(stage);
            let scene = new JTopo.Scene(stage);
            scene.background = 'http://www.jtopo.com/demo/img/bg.jpg';

            let getNode = (() => {
                let set = {};
                return ((id) => {
                    if (set[id]) return set[id];
                    let cat = all_cats_info[id] || {};
                    let name = cat.b || cat.c || id;
                    let node = set[id] = new JTopo.Node(name);
                    node.fillColor = JTopo.util.randomColor();
                    cat.aa && node.setImage('/img/cat/' + cat.aa);
                    scene.add(node);
                    return node;
                });
            })();
            let color1 = JTopo.util.randomColor();
            let color2 = JTopo.util.randomColor();
            for (let relation in r) {
                relation = r[relation];
                if (typeof relation !== 'object') continue;
                let c1 = relation.w,
                    c2 = relation.x;
                let i1 = relation.y,
                    i2 = relation.z;
                if (!c1 || !c2 || !i1) continue;
                let link = new JTopo.CurveLink(getNode(c1), getNode(c2), i1);
                link.lineWidth = 3; // 线宽
                link.strokeColor = c1 === id ? color1 : color2;
                link.click(e => link.text = (link.text === i1 ? i2 : i1));
                scene.add(link);
            }
            scene.doLayout(JTopo.layout.TreeLayout('down', 30, 107));
        }
    });
}

function ageSelecterListener(tar) {
    let old = tar.nextSibling.value;
    let ele = '';
    for (let i = (tar.value === '0' ? 1 : 0); i <= 12; i++)
        ele += `<option value='${i}'${i==old?"selected='selected'":''}>${i}个月</option>`;
    $(tar.nextSibling).html(ele);
}

function editCatInfo(startEdit, saveConfirm) {
    if (startEdit) {
        const editMethod = {
            none: (d, name) => `<input type="text"class="editField"disabled="disabled"value="${d}"/>`,
            str: (d, name) => `<input type="text"class="editField"placeholder="${name}"value="${d}"/>`,
            img: (d, name) => `<input type="text"class="editField"placeholder="${name}"value="${d}"onclick="selectImg(this,'sub_${name}')"/>`,
            ENUM: field => {
                const values = getTableIndexValues('basic_info', field, true);
                return (d, name) => {
                    let hasValue, ele = '';
                    for (let key in values) hasValue |= key === d, ele += `<option value='${values[key]}'${key===d?"selected='selected'":''}>${key}</option>`;
                    return `<select class="editField">${ele}<option value='none'${hasValue?'':"selected='selected'"}>空</option></select>`
                }
            },
            DATE: isAge => {
                if (isAge) {
                    return (d, name) => {
                        d = toAgeData(d);
                        let EY = d.isEstimate ? d.extraYear : 0;
                        let EM = d.isEstimate ? d.extraMonth : 1;
                        let yEle = (() => {
                            let ele = '';
                            for (let i = 0; i <= 42; i++)
                                ele += `<option value='${i}'${i===EY?"selected='selected'":''}>${i}年</option>`;
                            return ele;
                        })();
                        let mEle = (() => {
                            let ele = '';
                            for (let i = 1; i <= 12; i++)
                                ele += `<option value='${i}'${i===EM?"selected='selected'":''}>${i}个月</option>`;
                            return ele;
                        })();
                        return `<div class="editField"><input style="width:99%;"type="date"value="${d.date}"><br><button type="button" class="btn btn-primary ${d.isEstimate?'active':''}" style="width:99%;"onclick="if ($(this).hasClass('active')){$(this).removeClass('active').html('估计年龄');$(this.nextSibling).hide();}else{$(this).addClass('active').html('取消估计年龄');$(this.nextSibling).show();}">${d.isEstimate?'取消估计年龄':'估计年龄'}</button><div ${d.isEstimate?'':'style="display:none"'}><select onchange="ageSelecterListener(this)"style="width:40%">${yEle}</select><select style="width:60%">${mEle}</select></div></div>`;
                    };
                } else return (d, name) => `<input type="date" class="editField" value="${parseDate(d)}">`;
            }
        }
        const cat = all_cats_info[id];
        const editType = key => {
            let c = getTableKeyClass(key);
            switch (c) {
                case 'enum':
                    return [editMethod.ENUM(toRealName(key)), 'ENUM'];
                case 'date':
                    return [editMethod.DATE(false), 'DATE'];
                case 'age':
                    return [editMethod.DATE(true), 'DATE_AGE'];
                default:
                    return c ? [c, c] : ['none', 'none'];
            }
        }
        // const editType = {
        //     a: ['none', 'none'],
        //     aa: ['img', 'img'],
        //     b: ['text', 'text'],
        //     c: ['text', 'text'],
        //     d: ['text', 'text'],
        //     f: ['text', 'text'],
        //     l: ['text', 'text'],
        //     n: ['text', 'text'],
        //     e: [editMethod.ENUM('color'), 'ENUM'],
        //     g: [editMethod.ENUM('sex'), 'ENUM'],
        //     h: [editMethod.ENUM('health'), 'ENUM'],
        //     i: [editMethod.ENUM('spay'), 'ENUM'],
        //     m: [editMethod.ENUM('type'), 'ENUM'],
        //     j: [editMethod.DATE(false), 'DATE'],
        //     k: [editMethod.DATE(true), 'DATE_AGE'],
        //     o: [editMethod.DATE(false), 'DATE'],
        //     ay: [editMethod.DATE(false), 'DATE']
        // }
        $("#sub_cat_info>span").each((index, ele) => {
            ele = $(ele);
            let key = ele.attr('data-key'),
                data = getRealData(key, cat[key]),
                typeInfo = editType(key),
                show = typeInfo[0],
                handle = typeInfo[1],
                field = ((show instanceof Function && show) || editMethod[show] || editMethod.none)(data.data || '', data.nameValue);
            /*console.log(data, data.data);*/
            ele.html(`<div>${data.name}</div>${field}`);
            ele.data('handler', handle);
        });
    } else {
        if (saveConfirm && !saveConfirm()) return window.location.reload();
        let data = { a: id };
        $("#sub_cat_info>span").each((index, ele) => {
            console.log(ele);
            let handler = (ele = $(ele)).data('handler');
            let key = ele.attr('data-key');
            switch (handler) {
                case 'none':
                    break;
                case 'text':
                case 'img':
                case 'DATE':
                    data[key] = ele.children('input').val();
                    if (data[key] === '') data[key] = null;
                    break;
                case 'ENUM':
                    data[key] = ele.children('select').val();
                    if (data[key] === 'none') data[key] = null;
                    break;
                case 'DATE_AGE':
                    {
                        let x = ele.children('div');
                        let date = x.children('input').val();
                        let isEstimate = x.children('button').hasClass('active');
                        let extraObj = x.children('div').children('select');
                        let extra = parseInt(extraObj[0].value) * 12 + parseInt(extraObj[1].value);
                        data[key] = toAgeNumber(date, isEstimate, extra);
                        console.log('DATE_AGE', data[key]);
                        if (data[key] === undefined) data[key] = null;
                    }
                    break;
            }

        });
        console.log(data);
        update_cat(data);
    }
}

function update_cat(data) {
    $.ajax({
        type: "POST",
        url: "/cats/update",
        cache: 'false',
        data: data,
        beforeSend: req => req.setRequestHeader("x-access-token", localStorage.getItem("token")),
        success: res => {
            if (res.success) alert(`成功修改 ${id} 号猫咪!`);
            else alert(`发生错误:\n${res.error}  ${res.node||''}\n请检查!`);
            window.location.reload();
        }
    });
}

let photoPage = 0;
let photoEnd = false;

function getPhoto(id) {
    if (photoEnd) return;
    const __errorHandle = (obj, err, msg) => {
        $("#cat_photo").html(`<span><div>${err}</div>${msg}</span>`);
        photoPage--;
    };
    $.ajax({
        url: `/img/cats/${id}/${photoPage++}`,
        error: __errorHandle,
        success: (responseJSON) => {
            if (!responseJSON.success) return errorHandle('idCatPhotoError', responseJSON.error);
            let r = responseJSON.result;
            if (!r) return __errorHandle('', '不存在', `找不到ID为<span style="color:orange;">${id}</span>的猫咪`);

            console.log('getPhoto', `/img/cats/${id}/${photoPage-1}`, r, responseJSON.result);
            photoEnd |= !responseJSON.has;
            for (let i in r) {
                if (!r[i].hash) continue;
                $("#cat_photo").append(`<div data-hash="${r[i].hash}" class="module img-module"><img src="/img/cat/${r[i].hash}" /><span>${r[i].lore}</span></div>`);
            }
        }
    });
}

const runPrefixMethod = function(element, method) {
    var usablePrefixMethod;
    ["webkit", "moz", "ms", "o", ""].forEach(function(prefix) {
        if (usablePrefixMethod) return;
        if (prefix === "") {
            // 无前缀，方法首字母小写
            method = method.slice(0, 1).toLowerCase() + method.slice(1);
        }
        var typePrefixMethod = typeof element[prefix + method];
        if (typePrefixMethod + "" !== "undefined") {
            if (typePrefixMethod === "function") {
                usablePrefixMethod = element[prefix + method]();
            } else {
                usablePrefixMethod = element[prefix + method];
            }
        }
    });

    return usablePrefixMethod;
};

const id = (() => {
    let y = getQueryVariable('id');
    let x = parseInt(y);
    return isNaN(x) ? y : x;
})();

$(() => {
    getCat(id);
    // testJtopo();
    getRelation(id);
    getPhoto(id);

    $("#cat_photo").click(e => {
        let tar = $(e.target);
        tar = tar.hasClass('img-module') ? tar : $(tar.parent('.img-module'));
        let hash = tar.attr('data-hash');
        if (hash && typeof onClickImg === 'function') onClickImg(hash);
    });

    $.get("/img/cat-rand?limit=3&cid=" + id, r => {
        if (!r.success) return;
        for (let i = 0; i < 3 && i < r.result.length; i++) {
            let hash = r.result[i].hash;
            $(`#head_carousel .carousel-inner img:eq(${i})`).attr('src', '/img/cat/' + hash);
        }
    });
});

function onScrollBottom() {
    getPhoto(id);
}

function selectImg(target, back) {
    window.location.hash = 'cat_photo';
    onClickImg = hash => {
        $(target).val(hash.substring(2));
        back && (window.location.hash = back);
        onClickImg = null;
    }
}
let onClickImg;